import 'package:flutter/material.dart';
import '../models/course.dart';
import '../services/course_service.dart';
import '../widgets/course_card.dart';
import '../theme/colors.dart';
import 'course_detail_screen.dart';

class EducationScreen extends StatefulWidget {
  const EducationScreen({super.key});

  @override
  State<EducationScreen> createState() => _EducationScreenState();
}

class _EducationScreenState extends State<EducationScreen> {
  final CourseService _courseService = CourseService();
  List<Course> _courses = [];
  List<Course> _filteredCourses = [];
  CourseCategory _currentCategory = CourseCategory.all;
  bool _isLoading = true;
  String _searchQuery = '';

  @override
  void initState() {
    super.initState();
    _loadCourses();
  }

  Future<void> _loadCourses() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final courses = await _courseService.getAllCourses();
      setState(() {
        _courses = courses;
        _filteredCourses = courses;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载课程失败: $e')),
        );
      }
    }
  }

  void _filterCourses(CourseCategory category) async {
    setState(() {
      _currentCategory = category;
      _isLoading = true;
    });

    try {
      final courses = await _courseService.getCoursesByCategory(category);
      setState(() {
        _filteredCourses = courses;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _searchCourses(String query) {
    setState(() {
      _searchQuery = query;
      if (query.isEmpty) {
        _filteredCourses = _courses;
      } else {
        _filteredCourses = _courses
            .where((course) =>
                course.title.toLowerCase().contains(query.toLowerCase()) ||
                course.description.toLowerCase().contains(query.toLowerCase()))
            .toList();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.background,
      appBar: AppBar(
        title: const Text('教育培训'),
        backgroundColor: ThemeColors.primary,
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: Column(
        children: [
          // 搜索栏
          Container(
            padding: const EdgeInsets.all(16),
            color: Colors.white,
            child: TextField(
              onChanged: _searchCourses,
              decoration: InputDecoration(
                hintText: '搜索课程...',
                prefixIcon: const Icon(Icons.search),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                fillColor: ThemeColors.background,
              ),
            ),
          ),
          // 分类标签
          Container(
            height: 50,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: ListView(
              scrollDirection: Axis.horizontal,
              children: CourseCategory.values.map((category) {
                final isSelected = _currentCategory == category;
                return Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child: FilterChip(
                    label: Text(_getCategoryLabel(category)),
                    selected: isSelected,
                    onSelected: (_) => _filterCourses(category),
                    backgroundColor: Colors.white,
                    selectedColor: ThemeColors.primary.withOpacity(0.2),
                    checkmarkColor: ThemeColors.primary,
                  ),
                );
              }).toList(),
            ),
          ),
          // 课程列表
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _filteredCourses.isEmpty
                    ? const Center(
                        child: Text(
                          '暂无课程',
                          style: TextStyle(fontSize: 16, color: Colors.grey),
                        ),
                      )
                    : ListView.builder(
                        padding: const EdgeInsets.all(16),
                        itemCount: _filteredCourses.length,
                        itemBuilder: (context, index) {
                          final course = _filteredCourses[index];
                          return Padding(
                            padding: const EdgeInsets.only(bottom: 16),
                            child: CourseCard(
                              course: course,
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => CourseDetailScreen(
                                      courseId: course.id,
                                    ),
                                  ),
                                );
                              },
                            ),
                          );
                        },
                      ),
          ),
        ],
      ),
    );
  }

  String _getCategoryLabel(CourseCategory category) {
    switch (category) {
      case CourseCategory.all:
        return '全部';
      case CourseCategory.traditional:
        return '传统技艺';
      case CourseCategory.folk:
        return '民俗文化';
      case CourseCategory.music:
        return '音乐舞蹈';
      case CourseCategory.craft:
        return '手工艺术';
      case CourseCategory.literature:
        return '文学历史';
      case CourseCategory.philosophy:
        return '哲学思想';
    }
  }
}